package com.company.project.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.math.BigInteger;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import org.apache.log4j.Logger;
import org.apache.shiro.crypto.hash.SimpleHash;


public class MD5Utilts 
{
	protected static Logger logger = Logger.getLogger(MD5Utilts.class);

	public static String createMD5String(String str) 
	{
		return createMD5String(str.getBytes());
	}

	public static String entrySysUserPassword(String password)
	{
		String user_code = "123";
		return new SimpleHash("SHA-1", user_code , password).toString(); // 密码加密
	}
	
	
	public static String createMD5String(byte[] bytes)
	{
		MessageDigest messageDisest;
		try
		{
			messageDisest = MessageDigest.getInstance("MD5");
			messageDisest.update(bytes);
			return bytesToHex(messageDisest.digest());
		} catch (NoSuchAlgorithmException e)
		{
			logger.error(e.getMessage(), e);
		}
		return "";
	}

	public static String createMD5String(File file)
	{
		String value = null;
		FileInputStream in = null;
		try
		{
			in = new FileInputStream(file);
			MappedByteBuffer byteBuffer = in.getChannel().map(FileChannel.MapMode.READ_ONLY, 0, file.length());
			MessageDigest md5 = MessageDigest.getInstance("MD5");
			md5.update(byteBuffer);
			value = bytesToHex(md5.digest());
//			BigInteger bi = new BigInteger(1, md5.digest());
//			value = bi.toString(16);
		} catch (Exception e)
		{
			logger.error(e.getMessage(), e);
		} finally
		{
			if (null != in)
			{
				try
				{
					in.close();
				} catch (IOException e)
				{
					logger.error(e.getMessage(), e);
				}
			}
		}
		return value;
	}

	public static String bytesToHex(byte[] buffer)
	{
		char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9','a', 'b', 'c', 'd', 'e', 'f' };
		StringBuffer stringbuffer = new StringBuffer(2 * buffer.length);
		int k = buffer.length;
		for (int l = 0; l < k; l++)
		{
			byte bt = buffer[l];
			char c0 = hexDigits[(bt & 0xf0) >> 4];
			char c1 = hexDigits[bt & 0xf];
			stringbuffer.append(c0);
			stringbuffer.append(c1);
		}
		return stringbuffer.toString();
	}
	
	public static void main(String[] args)
	{
		String str = "111222000"  +"intrech" + "000";
		str = "111222333intrech333";
		System.out.println(createMD5String(str));
	}
}
